package com.ad.pet.app.recharge;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ad.pet.DaggerMainActivityCompent;
import com.ad.pet.Logger;
import com.ad.pet.MainActivity;
import com.ad.pet.R;
import com.ad.pet.app.Navigation;
import com.ad.pet.app.RxDisposable;
import com.ad.pet.app.account.order.fragment.PacketInfoContract;
import com.ad.pet.app.account.order.fragment.PacketInfoPresenter;
import com.ad.pet.common.data.utils.ui.DialogUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.events.Events;
import com.ad.pet.common.structure.events.RxBus;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.ui.activity.AppToolbarActivity;
import com.ad.pet.constant.Constant;
import com.ad.pet.models.remote.PayResult;
import com.ad.pet.models.remote.Wxpay;
import com.ad.pet.models.remote.account.order.PayCompleted;
import com.ad.pet.models.remote.account.order.PayMethodAll;
import com.ad.pet.models.remote.account.order.PayUrl;
import com.ad.pet.models.remote.account.order.SignCheck;
import com.ad.pet.models.remote.recharge.ReponseWeixin;
import com.ad.pet.models.result.ResultBean;
import com.ad.pet.ui.SimpleDividerDecoration;
import com.ad.pet.ui.TimeLabelZTextview;
import com.ad.pet.utils.LyxUtils;
import com.ad.pet.wxapi.WXPayUtils;
import com.alipay.sdk.app.PayTask;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import rx.functions.Action1;

//import com.jiuhe.handi.wxapi.WXPayUtils;

/**
 * 支付选择
 * Created by SEELE on 2018/6/4.
 */

public class RechargeActvity extends AppToolbarActivity implements PacketInfoContract.View {


    @BindView(R.id.btn_cash)
    TextView mBtnCash;

    @BindView(R.id.recycler_pay_item)
    RecyclerView mRecyclerPay;

    @BindView(R.id.tv_other_method)
    TextView tvOthberMethod;

    @BindView(R.id.tv_transer_title)
    TextView tvTranserTitle;

    @BindView(R.id.tv_transer_account)
    TextView tvTranserAccount;
    @BindView(R.id.tv_no_method_title)
    TextView tvNomethodTitle;

    @BindView(R.id.et_advice)
    EditText etAdvice;


    @BindView(R.id.tv_number)
    TextView mTvNumber;

    @BindView(R.id.tv_date)
    TextView mTvDate;

    @BindView(R.id.tv_unpay_time)
    TextView mTvUpadTime;
    @BindView(R.id.tv_reduce_price)
    TextView mTvReducePrice;
    @BindView(R.id.tv_time)
    TimeLabelZTextview mTvTime;
    @BindView(R.id.linear_pay_tips)
    LinearLayout mLinearPayTips;
    @BindView(R.id.relative_bazhe)
    RelativeLayout mRelativeBazhe;


    private RechargeAdapter mRechargeAdapter;


    @BindView(R.id.iv_pay_other)
    ImageView mIvPayOther;

    private PayMethodAll mPayMethodAll;

    ProgressDialog mLoadingDialog = null;

    @Inject
    PacketInfoPresenter mPacketInfoPresenter;

    @BindView(R.id.tv_count)
    TextView mTvCount;

    int position = -1;

    @BindView(R.id.btn_commit)
    Button mBtnCommit;
    private String mSn_id;

    @BindView(R.id.linear_pay)
    LinearLayout mLinearPay;

    @BindView(R.id.iv_device)
    ImageView mIvDivcie;
    @BindView(R.id.relative_advice)
    RelativeLayout mRelativeAdvice;
    @BindView(R.id.linear_advice)
    LinearLayout mLinearAdvice;
    @Inject
    RxDisposable mRxDisposable;

    boolean isShow;

    static final int SDK_PAY_FLAG = 1;
    private Handler deliver = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    String notifyUrl = payResult.getNotifyUrl();
                    // 判断resultStatus 为9000则代表支付成功
                    Logger.e("result_alipay:" + resultInfo + "|" + resultStatus + "|" + notifyUrl);
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。

                        ToastUtil.getToastUtil().showShort(getString(R.string.pay_success));
//17166573284
                        Navigation.goCompleteOrder(mActivity, mSn_id);
                        setResult(RESULT_OK, new Intent());
                        finish();
//                        RxBus.getDefault().post(new Events.PayStatusCallback(notifyUrl, "alipay", resultInfo));
                    } else {//支付失败
                        ToastUtil.getToastUtil().showShort(getString(R.string.pay_failed));

                    }
                    break;
            }
        }
    };
    private boolean mIsTitleShow;

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        mToolbar.setTitle(getString(R.string.pay));
        mStatusLayoutManager.showContent();
    }

    @Override
    protected int contentLayout() {
        return R.layout.activity_recharge;
    }

    @Override
    protected void clickRetry(View v) {

    }

    @Override
    protected void initViews() {
        mPacketInfoPresenter.onCreate(this);
        mLoadingDialog = DialogUtil.createProgressDialog(mActivity, getString(R.string.loading));
        mSn_id = getIntent().getStringExtra(Constant.ORDER_SN);
        mPacketInfoPresenter.getPayWays(mSn_id);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
        SimpleDividerDecoration simpleDividerDecoration = new SimpleDividerDecoration(mActivity, 5, R.color.bg_color);
        mRecyclerPay.addItemDecoration(simpleDividerDecoration);
        mRecyclerPay.setLayoutManager(linearLayoutManager);
        mRechargeAdapter = new RechargeAdapter(null);
        mRecyclerPay.setAdapter(mRechargeAdapter);



    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvents() {


        mRechargeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (mPayMethodAll != null) {
                    mRechargeAdapter.setChoseRecharge(position);
                    RechargeActvity.this.position = position;
                    mTvCount.setText(mPayMethodAll.getPay_method_list().get(position).getCurrency_symbol() + mPayMethodAll.getPay_method_list().get(position).getCurrency_total());

                }
            }
        });


        mLinearPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!hasLogin()) {
                    Navigation.goLogin(mActivity, 111, 0);
                    return;
                }
                if (position == -1) {
                    ToastUtil.getToastUtil().showShort(getString(R.string.please_chose_pay_way));
                    return;
                }

                mPacketInfoPresenter.createOrder("1", mPayMethodAll.getAmount(), mPayMethodAll.getPay_method_list().get(position).getPm_id(), mPayMethodAll.getOrder_sn(), mPayMethodAll.getUid(), mPayMethodAll.getPay_sign());

                //                Navigation.goCompleteOrder(mActivity);


            }
        });
        mBtnCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(etAdvice.getText().toString())) {
                    ToastUtil.getToastUtil().showShort(etAdvice.getHint().toString());
                    return;
                }
                mPacketInfoPresenter.addPayAdvice(mPayMethodAll.getOrder_sn(), etAdvice.getText().toString());
            }
        });

        tvOthberMethod.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isShow = !isShow;
                setRightView(isShow ? R.drawable.ic_cahr_up : R.drawable.ic_cahr_down);
                tvTranserTitle.setVisibility(isShow ? View.VISIBLE : View.GONE);
                tvTranserAccount.setVisibility(isShow ? View.VISIBLE : View.GONE);
            }
        });

        tvNomethodTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mIsTitleShow = !mIsTitleShow;
                mIvDivcie.setImageResource(mIsTitleShow ? R.drawable.ic_cahr_up : R.drawable.ic_cahr_down);
                mRelativeAdvice.setVisibility(mIsTitleShow ? View.VISIBLE : View.GONE);
                mLinearAdvice.setVisibility(mIsTitleShow ? View.VISIBLE : View.GONE);
            }
        });

        mRxDisposable.add(RxBus.getDefault().toObservable(Events.PayStatusCallback.class)
                .subscribe(new Action1<Events.PayStatusCallback>() {
                    @Override
                    public void call(Events.PayStatusCallback s) {
                        if ("weixin_app".equals(s.paytype)) {
                            ToastUtil.getToastUtil().showShort(getString(R.string.pay_success));
                            Navigation.goCompleteOrder(mActivity, mSn_id);
                            setResult(RESULT_OK, new Intent());
                            finish();
                        }
                    }
                }));
    }


    @Override
    public void initInject() {
        DaggerMainActivityCompent.builder().applicationComponent(getApplicationComponent())

                .activityModule(getActivityModule()).build().inject(this);
    }

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }


    @Override
    public void showLoading() {
        mLoadingDialog.show();
    }

    @Override
    public void hideLoading() {
        mLoadingDialog.dismiss();
    }

    @Override
    public void error(String msg) {
        ToastUtil.getToastUtil().showShort(msg);
    }

    @Override
    public void error(int code, String msg) {
        ToastUtil.getToastUtil().showShort(msg);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null)
            return;
        switch (requestCode) {

            case MainActivity.REQUEST_GO_MALL:
                setResult(RESULT_OK, new Intent());
                finish();

                break;

        }
    }

    @Override
    public void onConfirmReciveSuccess(ResultBean resultBean) {

    }


    @Override
    public void onCommentSuccess(ResultBean resultBean) {

    }

    @Override
    public void createOrderSuccess(final PayUrl payUrl) {
//        Navigation.goCommonWebView(mActivity,getString(R.string.pay),payUrl,false,MainActivity.REQUEST_GO_MALL,mSn_id);

        //付费成功  请将示例中的userid-safei替换成用户的用户id；请将100023467替换成流水号，如订单号或时间戳;请将”测试物品”替换成用户准备购买的装备名称或购买的实际内容；请将100替换成购买的金额。
        Map successPayMap = new HashMap();
        successPayMap.put("userid", LyxUtils.md5(getAccessToken(), "e828854e53b93a3b1e19c4cab2de707a"));
        successPayMap.put("orderid", mSn_id);
        successPayMap.put("item", "付费商品");
        successPayMap.put("amount", String.valueOf((int) (Double.valueOf(mPayMethodAll.getPay_method_list().get(position).getCurrency_total()) * 100)));
        MobclickAgent.onEvent(mActivity, "__finish_payment", successPayMap);

        if ("alipay".equals(payUrl.getPm_id())) {
            final String orderInfo = payUrl.getPay_url().toString();   // 订单信息

            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    PayTask alipay = new PayTask(mActivity);
                    Map<String, String> result = alipay.payV2(orderInfo, false);
                    result.put("notify_url", payUrl.getNotify_url());
                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    deliver.sendMessage(msg);
                }
            };
            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();
        } else if ("wechat_pay".equals(payUrl.getPm_id())) {
            WXPayUtils wxPayUtils = new WXPayUtils(mActivity);
            if (wxPayUtils.isWxAppInstalledAndSupported()) {

                String jsonString = new Gson().toJson(payUrl.getPay_url());
                ReponseWeixin weixin = new Gson().fromJson(jsonString, ReponseWeixin.class);
                Wxpay wxpay = new Wxpay(weixin.getAppid(), weixin.getPartnerid(), weixin.getPrepayid(), weixin.getNoncestr(), weixin.getTimestamp(), weixin.getPackages(), weixin.getSign(), payUrl.getNotify_url());
                wxPayUtils.doPay(new Gson().toJson(wxpay));
                Logger.d("jsonString--->" + new Gson().toJson(wxpay));
            }


        } else {
            Navigation.goPayWebView(mActivity, payUrl.getPay_url().toString(), mSn_id);
            setResult(RESULT_OK, new Intent());
            finish();
        }


    }

    @Override
    public void getPayWaysSuccess(final PayMethodAll payMethodAll) {
        mPayMethodAll = payMethodAll;
//        if (mPayMethodAll.getPay_method_list().size() > 0) {
//            mPayMethodAll.getPay_method_list().get(0).setChose(true);
//        }
//        mTvCount.setText(mPayMethodAll.getPay_method_list().get(0).getCurrency_symbol() + payMethodAll.getAmount());
        if (mPayMethodAll.getPay_method_list().size() > 0) {
//            mPayMethodAll.getPay_method_list().get(0).setChose(true);
//            this.position = 0;
            mTvCount.setText(mPayMethodAll.getPay_method_list().get(0).getCurrency_symbol() + mPayMethodAll.getPay_method_list().get(0).getCurrency_total());
        }
        mRechargeAdapter.setNewData(mPayMethodAll.getPay_method_list());
        tvOthberMethod.setText(payMethodAll.getLang().getPay_method_other().getTitle());
        tvTranserTitle.setText(payMethodAll.getLang().getPay_method_other().getDesc());
        String m = payMethodAll.getLang().getPay_method_other().getDesc2();

        mTvUpadTime.setText(payMethodAll.getLang().getTariff().get(0) + " + " + payMethodAll.getLang().getTariff().get(1));
        tvTranserAccount.setText(Html.fromHtml(m.replaceAll("\\\\n", "<br>")));

        tvNomethodTitle.setText(payMethodAll.getLang().getPay_method_feedback().getTitle());
        etAdvice.setHint(payMethodAll.getLang().getPay_method_feedback().getDesc());
        mBtnCash.setText(payMethodAll.getLang().getPay_method_feedback().getButton());
        mTvNumber.setText(payMethodAll.getOrder_sn());
        mTvDate.setVisibility(View.GONE);


        if (payMethodAll.getIs_show_first_order_return()==1){
            mTvTime.setDownTimeStart(payMethodAll.getFirst_order_return_residue_time(), new TimeLabelZTextview.onDownTimeLinstener() {
                @Override
                public void onTimeEnd() {
                    mLinearPayTips.setVisibility(View.GONE);

                }
            });
//            mTvReducePrice.setText(payMethodAll.getCurrency_symbol()+payMethodAll.getMoney_saved());

            mRelativeBazhe.setVisibility(View.VISIBLE);
        }else {
            mRelativeBazhe.setVisibility(View.GONE);
        }


    }

    @Override
    public void addPayAdvice() {
        ToastUtils.showLongToast(getString(R.string.add_pay_advice_success));
        etAdvice.setText("");
    }

    @Override
    public void payCompletedSuccess(PayCompleted payCompleted) {


    }

    @Override
    public void payCompletedOpenSuccess(SignCheck signCheck) {

    }


    void setRightView(int drawable) {
//        setCompoundDrawables(Drawable left,Drawable top,Drawable right,Drawable bottom)
//        Drawable可以通过 Drawable nav_up=getResources().getDrawable(R.drawable.button_nav_up);
        mIvPayOther.setImageResource(drawable);
    }


}
